package top.yokey.shopai.zcom.help;

import android.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import top.yokey.shopai.zcom.util.VerifyUtil;

@SuppressWarnings("ALL")
public class AesHelp {

    private static final String AES = "AES";
    private static final String UTF8 = "UTF-8";
    private static final String MODEL = "AES/ECB/PKCS5Padding";
    private static volatile AesHelp instance = null;

    private String keyword = "";

    public static AesHelp get() {

        if (instance == null) {
            synchronized (AesHelp.class) {
                if (instance == null) {
                    instance = new AesHelp();
                }
            }
        }
        return instance;

    }

    public void init(String keyword) {

        this.keyword = keyword;

    }

    public String encrypt(String content) {

        try {
            if (VerifyUtil.isEmpty(content)) {
                return "";
            }
            Cipher cipher = Cipher.getInstance(MODEL);
            cipher.init(Cipher.ENCRYPT_MODE, getSecretKeySpec());
            byte[] encrypt = cipher.doFinal(content.getBytes(UTF8));
            return Base64.encodeToString(encrypt, Base64.DEFAULT);
        } catch (Exception e) {
            return "";
        }

    }

    public String decrypt(String content) {

        try {
            if (VerifyUtil.isEmpty(content)) {
                return "";
            }
            Cipher cipher = Cipher.getInstance(MODEL);
            cipher.init(Cipher.DECRYPT_MODE, getSecretKeySpec());
            byte[] decrypt = Base64.decode(content.getBytes(UTF8), Base64.DEFAULT);
            return new String(cipher.doFinal(decrypt));
        } catch (Exception e) {
            return "";
        }

    }

    public SecretKeySpec getSecretKeySpec() {

        try {
            byte[] bytes = keyword.getBytes(UTF8);
            return new SecretKeySpec(bytes, AES);
        } catch (Exception e) {
            return new SecretKeySpec("".getBytes(), AES);
        }

    }

}
